use tauri::{
    menu::{Menu, MenuItem},
    tray::{MouseButton, TrayIconBuilder, TrayIconEvent},
    Manager,
};

use tauri::{AppHandle, Wry};

use crate::app_handle_manager::AppHandleManager;

pub fn try_register_tray_icon(app: &AppHandle<Wry>) -> tauri::Result<()> {
    let quit_i = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?;

    let menu = Menu::with_items(app, &[&quit_i])?;

    let tray = TrayIconBuilder::new()
        .icon(app.default_window_icon().unwrap().clone())
        .menu(&menu)
        .show_menu_on_left_click(false)
        .on_menu_event(move |app, event| match event.id.as_ref() {
            "quit" => {
                app.exit(0);
            }
            _ => {}
        })
        .on_tray_icon_event(move |_, event| {
            if let TrayIconEvent::Click {
                id: _,
                position: _,
                rect: _,
                button,
                button_state,
            } = event
            {
                if button == MouseButton::Left {
                    if let Some(window) = AppHandleManager::global()
                        .get_handle()
                        .get_webview_window("main")
                    {
                        window.show();
                    }
                }
            }
        })
        // .menu_on_left_click(true)
        .build(app).unwrap();
    AppHandleManager::global().set_tray(tray);
    Ok(())
}
